package com.example.diandian.service.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.diandian.service.edu.entity.Chapter;
import com.example.diandian.service.edu.entity.Video;
import com.example.diandian.service.edu.entity.vo.ChapterVo;
import com.example.diandian.service.edu.entity.vo.VideoVo;
import com.example.diandian.service.edu.mapper.ChapterMapper;
import com.example.diandian.service.edu.mapper.VideoMapper;
import com.example.diandian.service.edu.service.ChapterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author JTJ
 * @since 2020-07-19
 */
@Service
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, Chapter> implements ChapterService {

    @Autowired
    private VideoMapper videoMapper;



    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeChapterById(String id) {
        QueryWrapper<Video> chapterQueryWrapper = new QueryWrapper<>();
        chapterQueryWrapper.eq("chapter_id", id);
        videoMapper.delete(chapterQueryWrapper);
        return this.removeById(id);
    }

    @Override
    public List<ChapterVo> nestedList(String courseId) {

        List<ChapterVo> list = new ArrayList<>();
        //获取章信息
        QueryWrapper<Chapter> CqueryWrapper = new QueryWrapper<>();
        CqueryWrapper.eq("course_id", courseId);
        CqueryWrapper.orderByAsc("sort", "id");
        List<Chapter> chapters = baseMapper.selectList(CqueryWrapper);
        //获取课时信息
        QueryWrapper<Video> VqueryWrapper = new QueryWrapper<>();
        VqueryWrapper.eq("course_id", courseId);
        VqueryWrapper.orderByAsc("sort", "id");
        List<Video> videos = videoMapper.selectList(VqueryWrapper);

        for (int i = 0; i < chapters.size(); i++) {
            Chapter chapter = chapters.get(i);
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(chapter, chapterVo);
            list.add(chapterVo);
            List<VideoVo> Vlist = new ArrayList<>();
            for (int j = 0; j < videos.size(); j++) {
                Video video = videos.get(j);
                if (chapter.getId().equals(video.getChapterId())){
                    VideoVo videoVo = new VideoVo();
                    BeanUtils.copyProperties(video,videoVo);
                    Vlist.add(videoVo);
                }
            }
            chapterVo.setChildren(Vlist);
        }
        return list;
    }
}
